var parseManifest = require("parse-appcache-manifest");
var request = require('request');
var config = require("./config");

var x5UIPath = config.serverPath;

//http://192.168.1.49:8080/x5/$v@build_version@_no_$lzh_CN$s/UI2/SA/appcache/apps.j
//http://192.168.1.49:8080/x5/$v@build_version@_no_$lzh_CN$s/UI2/SA/appcache/getManifest.j?requestCacheApps=demo,SA,system,portal,test
var cacheManifest = function(callback){
    http://192.168.1.49:8080/x5/$v@build_version@_no_$lzh_CN$s/UI2/SA/appcache/apps.j
    var appsUrl = x5UIPath + "/"+config.serverName+"/"+config.modelName+"/SA/appcache/apps.j";
    console.log('\n 提前访问apps.j保证manifest能正常生成，通过url:' + appsUrl);
    var appsOptions = {
        url: appsUrl,
        headers: {
            'content-type':"application/json"
        }
    };
    request(appsOptions, function (error, response, body) {
         if(error){
            callback && callback(error);
         }else{
             var appcacheUrl = x5UIPath + "/"+config.serverName+"/"+config.modelName+"/SA/appcache/getManifest.j?requestCacheApps="+config.requestCacheApps;
             console.log('\n 开始读取manifest文件内容，通过url:' + appcacheUrl);
             var appcacheOptions = {
                 url: appcacheUrl,
                 headers: {
                     'content-type':"text/cache-manifest"
                 }
             };
             request(appcacheOptions, function (error, response, body) {
                 if (!error && response.statusCode == 200) {
                     console.log(body) // Print the google web page.
                     var entries = parseManifest(body);
                     var number = entries.cache.length;
                     for(var index in entries.cache){
                         var requestUrl = "http://127.0.0.1:"+ config.localPort + entries.cache[index];
                         request(requestUrl, function (error, response, body) {
                             if(!error && response.statusCode == 200){
                                 console.log("\n缓存"+ requestUrl + "成功!");
                                 number--;
                                 if(number == 0){
                                     callback && callback();
                                 }
                             }else{
                                 callback && callback(error);
                             }
                         });
                     }
                 }else if(error){
                     callback && callback(error);
                 }
             });
         }
    });
};
module.exports = cacheManifest;

